package com.web.boot.global.filter;

import com.blue.http.config.ErrorConfig;
import com.blue.http.invoke.InvokerFilter;
import com.blue.http.message.HttpRequest;
import com.blue.http.message.HttpResponse;
import com.blue.http.message.View;
import com.blue.http.util.HttpException;
import com.web.base.auth.facade.MenuAuthFacade;
import com.web.boot.global.model.User;
import com.web.boot.global.util.HttpContext;
import com.web.core.cache.ConfigCache;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;

/**
 * @author zhengjin
 * @since 1.0 2018年03月27日
 */
public class ContextFilter implements InvokerFilter
{
	@Autowired
	private MenuAuthFacade menuAuthFacade;
	@Resource
	private ConfigCache configCache;
	@Resource
	private HttpContext httpContext;

	private ErrorConfig errorConfig = ErrorConfig.getInstance();

	public ContextFilter()
	{
	}

	@Override
	public boolean preHandle(HttpRequest request, HttpResponse response) throws HttpException
	{
		User user = httpContext.getUser(request);
		if (user == null)
		{
			this.error(request, response, 1);
			return false;
		}

		response.param().put("user", user);
		String path = request.getUrl();

		if (path.startsWith("/index"))
			return true;

		if (!menuAuthFacade.auth(user.getId(), path))
		{
			this.error(request, response, 2);
			return false;
		}

		return true;
	}

	@Override
	public void afterHandle(HttpRequest request, HttpResponse response) throws HttpException
	{
	}

	private void error(HttpRequest request, HttpResponse response, int type)
	{
		int code = ErrorConfig.SESSION;
		String html = configCache.getValue("app_path") + "/app/login";
		if (type == 2) // 无权限访问
		{
			code = ErrorConfig.AUTH;
			html = "/html/403.html";
		}

		String ajax = request.getPost("_isAjax");
		if ("true".equals(ajax)) // 如果是ajax提交
		{
			response.setCode(code);
			response.setMsg(errorConfig.get(code));
		}
		else
		{
			View view = View.createBuilder().setLocation(html).build();
			response.setView(view);
		}



	}

}
